package com.yisen.dasan.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yisen.dasan.dao.QuestionnaireMapper;
import com.yisen.dasan.pojo.*;
import com.yisen.dasan.service.QuestionnaireService;
import com.yisen.dasan.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Console;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @AuthorList: LiuYiSen
 * @Date: 2020/10/21 12:22
 */
@Service
public class QuestionnaireServiceImpl implements QuestionnaireService {
    @SuppressWarnings("all")
    @Autowired
    QuestionnaireMapper questionnaireMapper;
    @Autowired
    Map<String,String> typeMap;
    @Autowired
    Map<String,String> resultMap;

    /**
     * 添加问卷调查表单
     * @param jsonObject
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean addForm(JSONObject jsonObject, HttpServletRequest request) {
//        User user = (User)request.getSession().getAttribute("user");
//        user = new User();// FIXME 模拟用户
//        user.setId(100001);
//        if (user == null){
//            return false;
//        }
//        int userId = user.getId();
//        System.out.println("测试...");
        String token = request.getHeader("token");
        int userId = Integer.parseInt(JWTUtils.verify(token).getClaims().get("id").asString());//后面加回去
        // 对表单表进行数据封装并插入
        int form_id = insertForm(jsonObject, userId);
        // 对表单项表进行数据封装并插入
        JSONArray form_text = jsonObject.getJSONArray("form_text");
        insertFormItem(form_text, form_id);
        return true;
    }

    /**
     * 用来插入表单表，并返回插入后的主键
     * @param jsonObject
     * @param userId
     * @return
     */
    private int insertForm(JSONObject jsonObject,int userId){
        Form form = new Form();
        form.setFormName(jsonObject.getString("form_name"));
        form.setFormDes(jsonObject.getString("form_tips"));
        form.setUserId(userId);
        form.setType(jsonObject.getInteger("form_type"));
        questionnaireMapper.addForm(form);
        return form.getId();
    }

    /**
     * 插入表单项表，并且调用方法来插入 选项
     * @param form_text
     * @param form_id
     * @return
     */
    private void insertFormItem(JSONArray form_text,int form_id){
        FormItem formItem = new FormItem();
        formItem.setFormId(form_id); // 设置外键值
        for(int i=0;i<form_text.size();i++){// 对表单项进行遍历
            JSONObject obj = form_text.getJSONObject(i);
            String type = obj.getString("type");
            formItem.setType(type);
            formItem.setTableName(typeMap.get(type));
            formItem.setResult(resultMap.get(type));
            formItem.setItemNum(i);
            formItem.setRequired(obj.getInteger("required"));
            formItem.setHide(obj.getInteger("hide"));
            formItem.setTitle(obj.getString("title"));
            formItem.setTips(obj.getString("tips"));
            formItem.setTipsColor(obj.getString("tips_color"));
            questionnaireMapper.addFormItem(formItem);
            // 对选项表进行数据封装并插入
            insertFormOption(obj.getString("option"), formItem.getId(), type);
        }
    }

    /**
     * 整合数据并插入选项表（对应不同特殊属性）
     * @param str
     * @param itemId
     * @param type
     */
    private void insertFormOption(String str,int itemId,String type){
        if (type.equals("radio")){
            JSONArray array = JSONArray.parseArray(str);
            ArrayList<FormRadio> list = new ArrayList<>();
            for (int i=0;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                FormRadio formRadio = new FormRadio();
                formRadio.setItemId(itemId);
                formRadio.setText(jsonObject.getString("text"));
                formRadio.setIsText(jsonObject.getInteger("isText"));
                list.add(formRadio);
            }
            questionnaireMapper.addFormRadio(list);
        }else if(type.equals("completion")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            FormCompletion completion = new FormCompletion();
            completion.setItemId(itemId);
            completion.setDef(jsonObject.getString("def"));
            completion.setPlaceholder(jsonObject.getString("placeholder"));
            completion.setMin(jsonObject.getInteger("min"));
            completion.setMax(jsonObject.getInteger("max"));
            questionnaireMapper.addFormCompletion(completion);
        }else if(type.equals("field")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            FormField formField = new FormField();
            formField.setItemId(itemId);
            formField.setDef(jsonObject.getString("def"));
            formField.setPlaceholder(jsonObject.getString("placeholder"));
            formField.setMin(jsonObject.getInteger("min"));
            formField.setMax(jsonObject.getInteger("max"));
            questionnaireMapper.addFormField(formField);
        }else if (type.equals("number")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            FormNumber formNumber = new FormNumber();
            formNumber.setItemId(itemId);
            formNumber.setDef(jsonObject.getString("def"));
            formNumber.setPlaceholder(jsonObject.getString("placeholder"));
            formNumber.setMin(jsonObject.getInteger("min"));
            formNumber.setMax(jsonObject.getInteger("max"));
            questionnaireMapper.addFormNumber(formNumber);
        }else if (type.equals("multiple")){
            JSONArray array = JSONArray.parseArray(str);
            JSONObject jsonObject0 = array.getJSONObject(0);
            int min = jsonObject0.getInteger("min");
            int max = jsonObject0.getInteger("max");
            ArrayList<FormMultiple> list = new ArrayList<>();
            for(int i=1;i<array.size();i++){
                FormMultiple formMultiple = new FormMultiple();
                formMultiple.setItemId(itemId);
                formMultiple.setMin(min);
                formMultiple.setMax(max);
                JSONObject jsonObject = array.getJSONObject(i);
                formMultiple.setText(jsonObject.getString("text"));
                formMultiple.setIsText(jsonObject.getInteger("isText"));
                list.add(formMultiple);
            }
            questionnaireMapper.addFormMultiple(list);
        }else if (type.equals("imgSingle")){
            JSONArray array=JSONArray.parseArray(str);
            ArrayList<FormImgRadio> list = new ArrayList<>();
            System.out.println(str);
            System.out.println(array.size());
            for(int i=0;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                FormImgRadio radio = new FormImgRadio(0, itemId, jsonObject.getString("imageUrl"), jsonObject.getString("text"));
                System.out.println(radio);
                list.add(radio);
            }
            questionnaireMapper.addFormImgRadio(list);
        }else if (type.equals("select")){
            JSONArray array=JSONArray.parseArray(str);
            List<Map> maps = array.toJavaList(Map.class);
            for (Map map : maps) {
                map.put("item_id", itemId);
            }
            questionnaireMapper.addSelect(maps);
        }else if (type.equals("name")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            FormName formName=new FormName();
            formName.setItemId(itemId);
            formName.setDef(jsonObject.getString("def"));
            formName.setPlaceholder(jsonObject.getString("placeholder"));
            formName.setMin(jsonObject.getInteger("min"));
            formName.setMax(jsonObject.getInteger("max"));
            questionnaireMapper.addName(formName);
        }else if (type.equals("gender")){
            JSONArray array = JSONArray.parseArray(str);
            List<Map> maps = array.toJavaList(Map.class);
            for (Map map : maps){
                map.put("item_id",itemId);
            }
            questionnaireMapper.addFormGender(maps);
        }else if (type.equals("education")){
            JSONArray jsonArray = JSONArray.parseArray(str);
            List<Map> maps = jsonArray.toJavaList(Map.class);
            for (Map map : maps){
                map.put("item_id",itemId);
            }
            questionnaireMapper.addFormEducation(maps);
        }else if (type.equals("age")){
            JSONArray jsonArray = JSONArray.parseArray(str);
            List<Map> maps = jsonArray.toJavaList(Map.class);
            for (Map map : maps){
                map.put("item_id",itemId);
            }
            questionnaireMapper.addFormAge(maps);
        }else if (type.equals("iphone")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            Map map = (Map) jsonObject;
            map.put("itemId",itemId);
            map.put("def",jsonObject.getString("def"));
            map.put("placeholder",jsonObject.getString("placeholder"));
            map.put("min",jsonObject.getInteger("min"));
            map.put("max",jsonObject.getInteger("max"));
            System.out.println("MAP::::::::::::::::::::::::::::::::::::::::"+map);
            questionnaireMapper.addFormIphone(map);
        }else if (type.equals("email")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            Map map = (Map) jsonObject;
            map.put("itemId",itemId);
            map.put("def",jsonObject.getString("def"));
            map.put("placeholder",jsonObject.getString("placeholder"));
            map.put("min",jsonObject.getInteger("min"));
            map.put("max",jsonObject.getInteger("max"));
            questionnaireMapper.addFormEmail(map);
        }else  if (type.equals("mobile")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            Map map = (Map) jsonObject;
            map.put("itemId",itemId);
            map.put("def",jsonObject.getString("def"));
            map.put("placeholder",jsonObject.getString("placeholder"));
            map.put("min",jsonObject.getInteger("min"));
            map.put("max",jsonObject.getInteger("max"));
            questionnaireMapper.addFormMobile(map);
        }else if (type.equals("birthday")){
            JSONObject jsonObject = JSONObject.parseObject(str);
            Map map = (Map) jsonObject;
            map.put("itemId",itemId);
            map.put("def",jsonObject.getString("def"));
            map.put("placeholder",jsonObject.getString("placeholder"));
            map.put("min",jsonObject.getInteger("min"));
            map.put("max",jsonObject.getInteger("max"));
            questionnaireMapper.addFormBirthday(map);
        }
    }

    @Override
    public boolean addCount(int formId) {
        int i = questionnaireMapper.addCount(formId);
        if(i==1){
            return true;
        }
        return false;
    }
}
